package net.sourceforge.j2meautonetwork.util;

import javax.microedition.lcdui.Displayable;

import net.sourceforge.j2meautonetwork.J2meAutoNetworkMIDlet;
import net.sourceforge.j2meautonetwork.view.DebugForm;
import net.sourceforge.j2meautonetwork.view.MainForm;

/**
 * 常用工具类，此类所有方法均为static final.
 * @author Steven King
 * @version 0.1
 */
public final class Utilities {

    public static final String replace(String s, String oldS, String newS) {
        int pos = s.indexOf(oldS);

        if (pos >= 0) {
            return s.substring(0, pos) + newS
                    + s.substring(pos + oldS.length());
        } else {
            return s;
        }
    }

    public static final String replaceAll(String s, String oldS, String newS) {
        int k = s.indexOf(oldS, 0);
        int l = 0;
        StringBuffer sb = new StringBuffer();
        while ((k = s.indexOf(oldS, l)) > -1) {
            sb.append(s.substring(l, k)).append(newS);
            l = k + oldS.length();
        }
        return sb.append(s.substring(l)).toString();
    }
    
    public static void debug(Throwable e) {
        debug(e.toString());
    }

    public static void error(Throwable e) {
        debug(e);
    }

    public static void error(String log) {
        debug(log);
    }

    public static void debug(String log) {
        System.out.println(log);
        DebugForm.getDebugForm(MainForm.getMainForm()).appendLog(log);
    }
    
    public static void debug(Displayable backHandle, String log){
        System.out.println(log);
        DebugForm.getDebugForm(MainForm.getMainForm()).appendLog(log);
        synchronized (log) {
            try {
                log.wait(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        J2meAutoNetworkMIDlet.getDisplay().setCurrent(backHandle);
    }

}
